package net.csdra.wenhua.nanan.qiandao.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import info.didyapp.weixin.UserInfoResponse;
import info.didyapp.weixin.WechatAdapter;
import net.csdra.wenhua.nanan.qiandao.domain.CheckIn;
import net.csdra.wenhua.nanan.qiandao.domain.User;
import net.csdra.wenhua.nanan.qiandao.service.AdminService;
import net.csdra.wenhua.nanan.qiandao.service.CheckInService;
import net.csdra.wenhua.nanan.qiandao.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Didy on 2016-02-15.
 */
@RestController
@RequestMapping("/qiandao")
public class WeixinRestController {

    private static final Logger log = LoggerFactory.getLogger(WeixinRestController.class);

    @Autowired
    UserService userService;
    @Autowired
    CheckInService checkInService;
    @Autowired
    AdminService adminService;
    @Autowired
    WechatAdapter wechatAdapter;

    @RequestMapping("/createUser")
    public User createUser(@ModelAttribute("currentUserId") String currentUserId, @RequestBody UserService.CreateUser createUser) {
        createUser.setWeixinId(currentUserId);
        return userService.createUser(createUser);
    }

    @RequestMapping("/updateUser")
    public User updateUser(@ModelAttribute("currentUserId") String currentUserId, @RequestBody UserService.UpdateUser updateUser) {
        updateUser.setWeixinId(currentUserId);
        return userService.updateUser(updateUser);
    }

    @RequestMapping("/getUserById")
    public User getUserById(String id) {
        return userService.getUserById(id);
    }

    @RequestMapping("/createCheckIn")
    public CheckIn createCheckIn(@ModelAttribute("currentUserId") String currentUserId) {
        CheckInService.CreateCheckIn createCheckIn = new CheckInService.CreateCheckIn();
        createCheckIn.setUserId(currentUserId);
        return checkInService.createCheckIn(createCheckIn);
    }

    @RequestMapping("/updadteCheckIn")
    public CheckIn updateCheckIn(@ModelAttribute("currentUserId") String currentUserId, @RequestBody CheckInService.UpdateCheckIn updateCheckIn) {
        updateCheckIn.setUserId(currentUserId);
        return checkInService.updateCheckIn(updateCheckIn);
    }

    @RequestMapping("/signIn")
    public CheckIn signIn(@ModelAttribute("currentUserId") String currentUserId) {
        User user = adminService.getUserByWeixinId(currentUserId);
        Assert.notNull(user);
        CheckInService.CreateCheckIn createCheckIn = new CheckInService.CreateCheckIn();
        createCheckIn.setUserId(user.getId());
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);
        Timestamp todayStart = new Timestamp(today.getTimeInMillis());
        List<CheckIn> checkInList = adminService.getCheckInListAfter(user.getId(), todayStart);
        CheckIn checkIn = null;
        if (checkInList.size() <= 0) {
            checkIn = checkInService.createCheckIn(createCheckIn);
        }
        return checkIn;
    }

    @RequestMapping("/getTotalAndContinuousNum")
    public CheckInService.CheckInReturn getTotalAndContinuousNum(@ModelAttribute("currentUserId") String currentUserId) {
        User user = adminService.getUserByWeixinId(currentUserId);
        Assert.notNull(user);

        boolean isSigned = false;
        int totalCheckInNum = 0;
        int continuousNum = 0;

        List<CheckIn> checkInListAll = checkInService.getCheckInListByUserId(user.getId());
        if (checkInListAll.size() == 0) {
            continuousNum = 0;
            totalCheckInNum = 0;
            isSigned = false;
        } else {
            totalCheckInNum = checkInListAll.size();

            Calendar today = Calendar.getInstance();
            Calendar lastDay = Calendar.getInstance();
            lastDay.add(Calendar.DAY_OF_MONTH, -1);
            Calendar recentDay = Calendar.getInstance();
            recentDay.setTimeInMillis(checkInListAll.get(0).getCheckInTime().getTime());

            isSigned = today.get(Calendar.DAY_OF_MONTH) == recentDay.get(Calendar.DAY_OF_MONTH) ? true : false;
            if (isSigned || recentDay.get(Calendar.DAY_OF_MONTH) == lastDay.get(Calendar.DAY_OF_MONTH)) {
                for (int index = 0; index < checkInListAll.size() - 1; index++) {
                    Timestamp currentDay = checkInListAll.get(index).getCheckInTime();
                    Timestamp preDay = checkInListAll.get(index + 1).getCheckInTime();
                    Calendar currentDate = Calendar.getInstance();
                    Calendar preDate = Calendar.getInstance();
                    currentDate.setTimeInMillis(currentDay.getTime());
                    preDate.setTimeInMillis(preDay.getTime());
                    currentDate.add(Calendar.DAY_OF_MONTH, -1);
                    if (currentDate.get(Calendar.DAY_OF_MONTH) == preDate.get(Calendar.DAY_OF_MONTH)) {
                        continuousNum++;
                    } else {
                        break;
                    }
                }
                continuousNum++;
            }
        }
        return new CheckInService.CheckInReturn(totalCheckInNum, continuousNum, user.getUserInfo(), isSigned);
    }

    @ModelAttribute("currentUserId")
    public String currentUserId(HttpSession session, WebRequest request, HttpServletRequest request1) {
        System.out.println("hahah" + request1.getSession().getAttribute("CURRENT_USER_ID"));
        String currentUserId = (String) session.getAttribute("CURRENT_USER_ID");
        System.out.println("2. CURRENT_USER_ID" + currentUserId);
        if (currentUserId == null) {
            throw new AccessDeniedException("请先登录");
        }
        return currentUserId;
    }

    @ExceptionHandler(AccessDeniedException.class)
    public void handleAccessDeniedException(AccessDeniedException ex, HttpServletResponse response, WebRequest request) throws IOException {
        response.sendError(401);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object exception(Exception ex) {
        if (StringUtils.hasText(ex.getMessage()) && ex.getMessage().startsWith("@")) {
            log.debug(ex.getMessage());
            return "\"" + ex.getMessage().substring(1) + "\"";
        } else {
            log.error(ex.getMessage(), ex);
            return "\"Error\"";
        }
    }
}
